import sys
import optparse
import pyglet
from pyglet.gl import *

parser = optparse.OptionParser()
option = parser.add_option
option('-s', '--size', dest='size', type='int', help='Map size')
opt, args = parser.parse_args()
assert len(args) == 1, 'expected a single image file argument'
assert opt.size, 'Map size not specified'

win = pyglet.window.Window()
glViewport(0, 0, win.width, win.height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, win.width, 0, win.height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
win.clear()
image = pyglet.image.load(args[0])
texture = image.get_texture()
glEnable(texture.target)
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

pyglet.graphics.draw(4, GL_QUADS,
	('v2i', (0, 0, opt.size, 0, opt.size, opt.size, 0, opt.size)),
	('t3f', texture.tex_coords),
	)
scaled = pyglet.image.Texture.create(opt.size, opt.size)
buffers = pyglet.image.get_buffer_manager()
color_buffer = buffers.get_color_buffer()
glReadBuffer(color_buffer.gl_buffer)
glEnable(scaled.target)
glBindTexture(scaled.target, scaled.id)
glCopyTexImage2D(scaled.target, scaled.level,
	GL_RGB, 0, 0, opt.size, opt.size, 0)

pixels = scaled.get_image_data().get_data('RGB', opt.size * 3)
win.flip()

pos = 0
lines = []
even = False
for y in range(opt.size):
	line = []
	add = line.append
	for x in range(opt.size):
		pixel = pixels[pos:pos+3]
		r = ord(pixel[0]); g = ord(pixel[1]); b = ord(pixel[2]) 
		if g > b and g > r:
			add('c')
		elif r > b:
			add('b')
		elif b > r and b > g:
			if g - r > 15:
				add('m')
			else:
				add('w')
		else:
			add('u')
		pos += 3
	lines.append(line)
lines.reverse()
for line in lines:
	print ''.join(line)
